package com.foot.travel.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.foot.travel.R;
import com.koalac.ironman.common.module.BaseActivity;
import com.koalac.ironman.util.DialogUtils;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.ScrollViewPager;
import com.shizhefei.view.indicator.FixedIndicatorView;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorPagerAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorViewPagerAdapter;

public class ShowImageActivity extends BaseActivity {

    @ViewInject(id = R.id.viewPager)
    ScrollViewPager mScrollViewPager;
    @ViewInject(id = R.id.indicator)
    FixedIndicatorView mFixedIndicatorView;
    private IndicatorViewPager mIndicatorViewPager;
    private ArrayList<String> mImageUrls = new ArrayList<String>();
    public static final String IMAGE_URLS_KEY = "image_url";
    public static final String IMAGE_URL_INDEX = "image_url_index";
    private LayoutInflater mLayoutInflater;
    private int mImageIndex = 0;;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_show_image);
	mImageUrls = getIntent().getStringArrayListExtra(IMAGE_URLS_KEY);
	mImageIndex = getIntent().getIntExtra(IMAGE_URL_INDEX, 0);
	mLayoutInflater = LayoutInflater.from(ShowImageActivity.this);
	mIndicatorViewPager = new IndicatorViewPager(mFixedIndicatorView,
		mScrollViewPager);
	mIndicatorViewPager.setAdapter(adapter);
	mIndicatorViewPager.setCurrentItem(mImageIndex, false);
    }

    private IndicatorPagerAdapter adapter = new IndicatorViewPagerAdapter() {

	@Override
	public View getViewForTab(int position, View convertView,
		ViewGroup container) {
	    if (convertView == null) {
		convertView = mLayoutInflater.inflate(R.layout.tab_guide,
			container, false);
	    }
	    return convertView;
	}

	@Override
	public View getViewForPage(int position, View convertView,
		ViewGroup container) {
	    if (convertView == null) {
		convertView = mLayoutInflater.inflate(R.layout.item_show_image,
			container, false);
	    }
	    final ImageView imageView = (ImageView) convertView
		    .findViewById(R.id.image);
	    Glide.with(ShowImageActivity.this)
		    .load(mImageUrls.get(position))
		    .listener(new RequestListener<String, GlideDrawable>() {

			@Override
			public boolean onException(Exception arg0, String arg1,
				Target<GlideDrawable> arg2, boolean arg3) {
			    return false;
			}

			@Override
			public boolean onResourceReady(GlideDrawable arg0,
				String arg1, Target<GlideDrawable> arg2,
				boolean arg3, boolean arg4) {
			    imageView
				    .setOnLongClickListener(new OnLongClickListener() {

					@Override
					public boolean onLongClick(View v) {
					    AlertDialog p = DialogUtils
						    .createConfirmDialog(
							    ShowImageActivity.this,
							    "",
							    "保存图片？",
							    "确定",
							    "取消",
							    new DialogInterface.OnClickListener() {

								@Override
								public void onClick(
									DialogInterface dialog,
									int which) {
								    File file = saveImage(loadBitmapFromView(imageView));
								    String filepath = file.getAbsolutePath();
								    toast("保存路径:"
									    + filepath);
								    dialog.dismiss();
								    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
								}
							    },
							    new DialogInterface.OnClickListener() {

								@Override
								public void onClick(
									DialogInterface dialog,
									int which) {
								    dialog.dismiss();
								}
							    },
							    DialogUtils.NO_ICON,
							    true);
					    p.show();
					    return false;
					}
				    });
			    return false;
			}
		    }).placeholder(R.drawable.ic_empty).crossFade()
		    .into(imageView);

	    // PhotoViewAttacher attacher = new PhotoViewAttacher(imageView);
	    // attacher.update();
	    imageView.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {
		    ShowImageActivity.this.finish();
		}
	    });
	    return convertView;
	}

	@Override
	public int getCount() {
	    return mImageUrls.size();
	}
    };

    public static Bitmap loadBitmapFromView(View v) {
	if (v == null) {
	    return null;
	}
	Bitmap screenshot;
	screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
		Config.ARGB_4444);
	Canvas c = new Canvas(screenshot);
	c.translate(-v.getScrollX(), -v.getScrollY());
	v.draw(c);
	return screenshot;
    }
    
    public static File saveImage(Bitmap bmp) {
	    File appDir = new File(Environment.getExternalStorageDirectory(), "foot_travel");
	    if (!appDir.exists()) {
	        appDir.mkdir();
	    }
	    String fileName = System.currentTimeMillis() + ".jpg";
	    File file = new File(appDir, fileName);
	    try {
	        FileOutputStream fos = new FileOutputStream(file);
	        bmp.compress(CompressFormat.JPEG, 100, fos);
	        fos.flush();
	        fos.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return file;
	}

}
